# .NET Project Build Script (PowerShell 5.1 compatible)
param(
    [string]$Configuration = "Release",
    [switch]$IncludeFrontend,
    [string]$ProjectPath
)

$ErrorActionPreference = "Stop"
$script:hasErrors = $false

function Find-NearestProject {
    param([string]$StartPath = ".")
    
    # Find .csproj files in current and parent directories
    $currentPath = $StartPath
    while ($currentPath -ne "") {
        $projects = Get-ChildItem -Path $currentPath -Filter "*.csproj" -Recurse | 
        Where-Object { $_.FullName -notlike "*\obj\*" -and $_.FullName -notlike "*\bin\*" }
        
        if ($projects) {
            # Prefer web projects
            $webProject = $null
            foreach ($proj in $projects) {
                if ((Get-Content $proj.FullName -Raw) -match "Microsoft.NET.Sdk.Web") {
                    $webProject = $proj
                    break
                }
            }
            
            if ($null -eq $webProject) {
                return $projects[0]
            }
            else {
                return $webProject
            }
        }
        
        $currentPath = Split-Path $currentPath -Parent
        if ($currentPath -eq $null) { break }
    }
    
    return $null
}

# Main execution flow
try {
    # Auto-detect project if not specified
    if (-not $ProjectPath) {
        $projectFile = Find-NearestProject
        if (-not $projectFile) {
            Write-Host "Error: No .NET project found in current or parent directories" -ForegroundColor Red
            $script:hasErrors = $true
            exit 1
        }
        $ProjectPath = $projectFile.FullName
    }

    Write-Host "Building project: $ProjectPath" -ForegroundColor Cyan

    # Set unified output directory
    $outputDir = ".\BuildProject\backend"
    $publishDir = "$outputDir\publish"

    # Create/clean output directory
    if (-not (Test-Path $outputDir)) {
        New-Item -ItemType Directory -Path $outputDir | Out-Null
    }
    else {
        Remove-Item "$outputDir\*" -Recurse -Force -ErrorAction SilentlyContinue
    }

    # Restore dependencies
    Write-Host "Restoring project dependencies..." -ForegroundColor Cyan
    dotnet restore $ProjectPath
    if ($LASTEXITCODE -ne 0) { throw "Dependency restore failed" }

    # Build project
    Write-Host "Building project..." -ForegroundColor Cyan
    dotnet build $ProjectPath -c $Configuration --no-restore
    if ($LASTEXITCODE -ne 0) { throw "Build failed" }

    # Publish project
    Write-Host "Publishing project..." -ForegroundColor Cyan
    dotnet publish $ProjectPath -c $Configuration -o $publishDir --no-build
    if ($LASTEXITCODE -ne 0) { throw "Publish failed" }

    # Copy config files
    $projectDir = [System.IO.Path]::GetDirectoryName($ProjectPath)
    Copy-Item "$projectDir\appsettings*" $publishDir -Force -ErrorAction SilentlyContinue

    # Create zip package
    $projectName = [System.IO.Path]::GetFileNameWithoutExtension($ProjectPath)
    $zipFile = "$outputDir\$projectName-$(Get-Date -Format 'yyyyMMdd-HHmmss').zip"
    
    Write-Host "Creating package: $zipFile" -ForegroundColor Cyan
    Compress-Archive -Path "$publishDir\*" -DestinationPath $zipFile -Force
    if (-not $?) { throw "Package creation failed" }

    Write-Host "Build completed successfully!" -ForegroundColor Green
    Write-Host "Package created at: $(Resolve-Path $zipFile)" -ForegroundColor Green
}
catch {
    Write-Host "Build failed: $_" -ForegroundColor Red
    $script:hasErrors = $true
}

if ($script:hasErrors) {
    Write-Host "Build process encountered errors, please check above messages" -ForegroundColor Red
}

Read-Host "Press Enter to exit..."
